package com.platform.internal;

import java.io.Serializable;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Order;

/**
 * List contains {@link order}for hibernate HQL (Hibernate Query Languge) use,
 * use the method {@link #toString()} to get a HQL "order by" query.
 * 
 */
public class OrderList implements Serializable {

	private static final long serialVersionUID = 6533900289640474987L;

	/** Logger for this class */
	private static final Logger LOG = Logger.getLogger(OrderList.class);

	/** order arrylist */
	private ArrayList<Order> orders = new ArrayList<Order>();

	/**
	 * Default Constructor for OrderList.
	 * 
	 */
	public OrderList() {
		// do nothing
	}

	/**
	 * Constructor for OrderList.
	 * 
	 * @param order
	 *            DOCUMENT ME!
	 */
	public OrderList(final Order order) {
		this.orders.add(order);
	}

	/**
	 * Render the HBM order
	 * 
	 * @return DOCUMENT ME!
	 */
	@Override
	public String toString() {
		String result = "";

		int valideOrderCount = 0;
		final int size = this.orders.size();

		for (int i = 0; i < size; i++) {
			if (valideOrderCount > 0) {
				result = result + ",";
			}

			if (this.orders.get(i) != null) {
				result = result + " obj." + this.orders.get(i);
				valideOrderCount++;
			}
		}

		if (valideOrderCount > 0) {
			result = " order by " + result;
		}

		if (OrderList.LOG.isDebugEnabled()) {
			OrderList.LOG.debug("toString() - Order query:" + result);
		}

		return result;
	}

	/**
	 * add a order to the list
	 * 
	 * @param order
	 */
	public void add(final Order order) {
		this.orders.add(order);
	}

	/**
	 * remove a order form the Orderlist
	 * 
	 * @param order
	 */
	public void remove(final Order order) {
		this.orders.remove(order);

		final int size = this.orders.size();

		if (size != 0) {
			for (int i = 0; i < size; i++) {
				if (this.orders.get(i).toString().equals(order.toString())) {
					this.orders.remove(i);

					if (OrderList.LOG.isDebugEnabled()) {
						OrderList.LOG.debug("removed a order [" + order
						        + "] from a OrderList at the position " + i);
					}

					break;
				}
			}
		}
	}

	public void clear() {
		this.orders.clear();
	}

	/**
	 * DOCUMENT ME!
	 * 
	 * @return DOCUMENT ME!
	 */
	public int size() {
		return this.orders.size();
	}
}
